import java.util.ArrayList;
import java.util.LinkedList;
import java.awt.*;
import java.awt.event.*;

import javax.swing.*;

class Game extends JFrame implements ActionListener, KeyListener {
	protected final DrawingZone dz;
	protected final ArrayList<Snake> snakes;
	protected static final double directions[] = new double[]{3*Math.PI/2, 0, Math.PI/2, Math.PI};
	protected static final char keymap[] = new char[]{'z', 'd', 's', 'q', '8', '6', '5', '4', 'i', 'l', 'k', 'j'};
	protected Timer tmrSize, tmrMove;

	public Game() {
		setSize(500, 500);
		setLocation(200, 200);
		setTitle("Snake");
		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setLocationRelativeTo(null);
		setLayout(new BoxLayout(getContentPane(), BoxLayout.Y_AXIS));
		addKeyListener(this);
		
		snakes = new ArrayList<Snake>();
		snakes.add(new Snake(0, 0, 5, 10, 15, Color.RED));
		snakes.add(new Snake(-30, 30, 5, 10, 15, Color.YELLOW));
		add(dz = new DrawingZone(snakes, Color.DARK_GRAY));
		
		tmrSize = new Timer(2000, this);
		tmrMove = new Timer(50, this);
		setVisible(true);
		tmrSize.start();
		tmrMove.start();
	}
	
	protected void updateSize() {
		for (Snake s: snakes)
			s.updateSize();
		dz.repaint();
	}
	
	protected void updatePosition() {
		for (Snake s: snakes)
			s.updatePosition();
		dz.repaint();
	}
	
	public void actionPerformed(ActionEvent e) {
		if (e.getSource() == tmrSize)
			updateSize();
		else if (e.getSource() == tmrMove)
			updatePosition();
	}
	
	public static void main(String[] args) {
		JFrame frm = new Game();
	}

	@Override public void keyPressed(KeyEvent e) {}
	@Override public void keyReleased(KeyEvent e) {}

	@Override
	public void keyTyped(KeyEvent e) {
		int pos;
		for (pos=0; pos<keymap.length; pos++)
			if (keymap[pos] == e.getKeyChar()) break;
		if (pos<keymap.length) {
			//valid key
			int id = pos / 4;
			int dir = pos % 4;
			snakes.get(id).changeDirection(directions[dir]);
		}
	}
}
